package com.agrimall.servlet.client;

import com.agrimall.entity.Product;
import com.agrimall.service.ProductService;
import com.agrimall.service.impl.ProductServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 客户端首页Servlet（合并商品预览功能）
 */
@WebServlet("/client/index")
public class ClientIndexServlet extends HttpServlet {
    private ProductService productService = new ProductServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            String pageStr = request.getParameter("page");
            String category = request.getParameter("category");
            String keyword = request.getParameter("keyword");
            
            int page = 1;
            if (pageStr != null && !pageStr.isEmpty()) {
                try {
                    page = Integer.parseInt(pageStr);
                } catch (NumberFormatException e) {
                    page = 1;
                }
            }
            int pageSize = 12;
            
            List<Product> products;
            int totalCount = 0;
            try {
                if (keyword != null && !keyword.isEmpty()) {
                    products = productService.searchProducts(keyword, page, pageSize);
                    totalCount = productService.countProductsByKeyword(keyword);
                } else if (category != null && !category.isEmpty()) {
                    products = productService.getProductListByCategory(category, page, pageSize);
                    totalCount = productService.countProductsByCategory(category);
                } else {
                    products = productService.getProductList(page, pageSize);
                    totalCount = productService.countAllProducts();
                }
                
                if (products == null) {
                    products = new java.util.ArrayList<>();
                }
            } catch (Exception e) {
                e.printStackTrace();
                products = new java.util.ArrayList<>();
                request.setAttribute("error", "查询商品失败：" + e.getMessage());
            }
            
            // 计算总页数
            int totalPages = (int) Math.ceil((double) totalCount / pageSize);
            if (totalPages == 0) {
                totalPages = 1; // 至少显示1页
            }
            
            // 判断是否有下一页
            boolean hasNextPage = page < totalPages;
            
            request.setAttribute("products", products);
            request.setAttribute("page", page);
            request.setAttribute("category", category);
            request.setAttribute("keyword", keyword);
            request.setAttribute("totalCount", totalCount);
            request.setAttribute("totalPages", totalPages);
            request.setAttribute("hasNextPage", hasNextPage);
            request.getRequestDispatcher("/client/index.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "数据加载失败：" + e.getMessage());
            request.getRequestDispatcher("/client/index.jsp").forward(request, response);
        }
    }
}
